// 需要安装：npm install express axios dotenv
const express = require('express');
const axios = require('axios');
const router = express.Router();
require('dotenv').config();

const DEEPSEEK_API_KEY = 'sk-014149ec651849f9810c84c3f55bde31';
const API_URL = 'https://api.deepseek.com/v1/chat/completions';

// 普通聊天接口
router.post('/deepseek/chat', async (req, res) => {
  try {
    const { messages } = req.body;
    
    const response = await axios.post(API_URL, {
      model: "deepseek-chat",
      messages: messages,
      temperature: 0.7,
      max_tokens: 1024,
      
    }, {
      headers: {
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });
    
    const aiReply = response.data.choices[0].message.content;
    res.json({ reply: aiReply });
    
  } catch (error) {
    console.error('DeepSeek API错误:', error.response?.data || error.message);
    res.status(500).json({ error: 'AI服务暂时不可用' });
  }
});

// 流式聊天接口

router.get('/deepseek/stream', async (req, res) => {
  try {
    const userMessage = req.query.message;
    
    // 设置SSE头
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': 'http://localhost:5173' // 改为你的前端URL
    });
    
    // 发送初始心跳
    res.write(':init\n\n');
    
    const response = await axios.post(API_URL, {
      model: "deepseek-chat",
      messages: [{ role: "user", content: userMessage }],
      stream: true,
      temperature: 0.7,
      max_tokens: 1024
    }, {
      headers: {
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      responseType: 'stream'
    });
    
    // 心跳机制
    const heartbeat = setInterval(() => {
      res.write(':heartbeat\n\n');
    }, 15000);
    
    response.data.on('data', chunk => {
      const lines = chunk.toString().split('\n').filter(line => line.trim());
      
      for (const line of lines) {
        if (line.startsWith('data: ') && !line.includes('[DONE]')) {
          try {
            const data = JSON.parse(line.replace('data: ', ''));
            if (data.choices && data.choices[0].delta.content) {
              res.write(`data: ${JSON.stringify({
                content: data.choices[0].delta.content
              })}\n\n`);
            }
          } catch (e) {
            console.error('解析错误:', e);
          }
        }
      }
    });
    
    response.data.on('end', () => {
      clearInterval(heartbeat);
      res.write('event: end\ndata: [DONE]\n\n');
      res.end();
    });
    
    response.data.on('error', err => {
      clearInterval(heartbeat);
      console.error('流错误:', err);
      res.write('event: error\ndata: ' + JSON.stringify({ error: 'Stream error' }) + '\n\n');
      res.end();
    });
    
    req.on('close', () => {
      clearInterval(heartbeat);
      response.data.destroy();
    });
    
  } catch (error) {
    console.error('DeepSeek流API错误:', error);
    res.write('event: error\ndata: ' + JSON.stringify({ error: 'API request failed' }) + '\n\n');
    res.end();
  }
});


module.exports = router;